<?php
/**
 * 支付宝支付异步回调处理
 * User: zym(wika)
 * Date: 2016/12/13
 * Time: 13:31
 */
class AlipayNotifyAction extends CommonAction
{
    public function _initialize(){

    }

	/**
	 * 支付宝服务窗手机网站支付异步处理
	 */
	public function notify()
	{
		$returnData = $_POST;
        wLog(date("Y-m-d H:i:s")." notify-1-returnData: ".var_export($returnData,true),"notify");
		if (!empty($returnData)) {
			// 存储支付返回的数据包（沿用院长做的支付宝扫码支付）
			$insert = array(
				'data' => json_encode($returnData),
				'create_time' => time(),
			);
			D('AlipayQrpayCallBack')->add($insert);
            wLog(date("Y-m-d H:i:s")." notify-2-_sql: ".var_export(D('AlipayQrpayCallBack')->_sql(),true),"notify");
            if($returnData['trade_status'] != "TRADE_FINISHED" && $returnData['trade_status'] != "TRADE_SUCCESS") { //没交易成功也没支付成功
                wLog('pay fail:'.var_export($returnData,true),'AlipayNotify');
                return false;
            }
			// 解析订单编号内的模块ID
			$orderSn = $returnData['out_trade_no'];
            wLog(date("Y-m-d H:i:s")." notify-3-orderSn: ".var_export($orderSn,true),"notify");
			$moduleId = substr($orderSn, 14, 3);
            wLog(date("Y-m-d H:i:s")." notify-4-moduleId: ".var_export($moduleId,true),"notify");
			$moduleId = preg_replace('/^0+/', '', $moduleId);
            wLog(date("Y-m-d H:i:s")." notify-5-moduleId: ".var_export($moduleId,true),"notify");
			// 获取对应模块信息
			$mModule = D('Module');
			$moduleInfo = $mModule->getByPk($moduleId);
            wLog(date("Y-m-d H:i:s")." notify-6-_sql: ".var_export($mModule->_sql(),true),"notify");
			/*if(!$moduleInfo || $moduleInfo['status'] != 0){
				// 消息模板通知开发者错误信息
				$this->notifyReponse();
			}*/

			// 获取对应订单
			$mOrder = D($moduleInfo['order_model_name']);
            wLog(date("Y-m-d H:i:s")." notify-7-mOrder: ".var_export($mOrder,true),"notify");
			$orderInfo = $mOrder->getByOrderSn($orderSn);
            wLog(date("Y-m-d H:i:s")." notify-8-orderInfo: ".var_export($orderInfo,true),"notify");
			/*if(!$orderInfo){
				// 消息模板通知开发者错误信息
				$this->notifyReponse();
			}*/

			$order = $mOrder->where(array('transaction_id' => $returnData['trade_no'], 'is_pay_notify' => 1))->find();
            wLog(date("Y-m-d H:i:s")." notify-9-mOrder: ".var_export($mOrder->_sql(),true),"notify");
			if (empty($order)) {
				// 更新支付状态
				$update = array(
					'order_id' => $orderInfo['order_id'],
					'status' => 2,
					'pay_type' => 5,
					'pay_time' => time(),
					'is_pay_notify' => 1,
					'transaction_id' => $returnData['trade_no'],
					'pay_notify_time' => time(),
				);
                if($moduleInfo['module_name'] == "QrcodeMore"){
                    $update['user_code'] = $returnData['buyer_logon_id'];
                }
                //支付宝存在使用集分宝或者红包的情况，一旦使用部分集分宝或者部分红包，支付宝会生成多笔
                $fund_bill_list_arr =  json_decode($returnData['fund_bill_list'],true);
                if($fund_bill_list_arr && count($fund_bill_list_arr)>1) {
                    $amont = 0;
                    $alipay_part_point = 0;
                    $alipay_part_coupon = 0;
                    $update['part_num'] = 0;
                    foreach ($fund_bill_list_arr as $k => $v) {
                        if ($v['fund_channel'] == 'POINT' && $v['amount'] < $returnData['total_amount']) {
                            $amont += $v['amount'];
                            $alipay_part_point = 1;
                        }
                        if ($v['fund_channel'] == 'MCOUPON' && $v['amount'] < $returnData['total_amount']) {
                            $amont += $v['amount'];
                            $alipay_part_coupon = 1;
                        }
                    }
                    //有可能存在使用（集分宝+红包）刚好全额付款的情况，只能算一笔
                    if ($amont == $returnData['total_amount']) {
                        $update['part_num'] = 1;
                        $update['alipay_part_point'] = 1;
                        $update['alipay_part_coupon'] = 1;
                    } elseif ($amont < $returnData['total_amount']) {
                        if ($alipay_part_point) {
                            $update['part_num']++;
                            $update['alipay_part_point'] = 1;
                        }
                        if ($alipay_part_coupon) {
                            $update['part_num']++;
                            $update['alipay_part_coupon'] = 1;
                        }
                    }
                }
                wLog(date("Y-m-d H:i:s")." notify-10-update: ".var_export($update,true),"notify");
				$resOrder = $mOrder->update($update);
                if($resOrder === false){
                    wLog('update order error:'.M()->_sql(),'AlipayNotify');
                    return false;
                }
                $mUser = D('User');
                if ($orderInfo['user_id'] || $orderInfo['uid']) {
                    wLog(date("Y-m-d H:i:s")." notify-11-orderInfo['user_id']: ".var_export($orderInfo['user_id'],true),"notify");
                    wLog(date("Y-m-d H:i:s")." notify-11-orderInfo['uid']: ".var_export($orderInfo['uid'],true),"notify");
                    $accountId = $mUser->getFieldByUserId($orderInfo['user_id'] ? $orderInfo['user_id'] : $orderInfo['uid'], 'account_id');
                } else {
                    $accountId = $orderInfo['account_id'];
                    wLog(date("Y-m-d H:i:s")." notify-11-accountId: ".var_export($accountId,true),"notify");
                }
                wLog(date("Y-m-d H:i:s")." notify-11-accountId: ".var_export($accountId,true),"notify");
                // 回调支付成功的方法
                R($moduleInfo['notify_method'], array($orderInfo['order_id'], $accountId));
                wLog(date("Y-m-d H:i:s")." notify-11-accountId: ".var_export($accountId,true),"notify");
//				// 平台支付总表插入支付记录
//				$mPay = D('Pay');
//				$mUser = D('User');
//                if ($orderInfo['user_id'] || $orderInfo['uid']) {
//                    $accountId = $mUser->getFieldByUserId($orderInfo['user_id'] ? $orderInfo['user_id'] : $orderInfo['uid'], 'account_id');
//                } else {
//                    $accountId = $orderInfo['account_id'];
//                }
//                $updatePay['account_id'] = $accountId ? $accountId : 0;
//				$updatePay['module_id'] = $moduleId;
//                $updatePay['user_id'] = $orderInfo['user_id'] ? $orderInfo['user_id'] : $orderInfo['uid'];
//                $updatePay['order_sn'] = $orderSn;
//                $updatePay['status'] = 1;
//                $updatePay['goods_amount'] = $orderInfo['goods_amount']?$orderInfo['goods_amount']:0;
//                $updatePay['order_amount'] = $returnData['receipt_amount']?$returnData['receipt_amount']:$updatePay['goods_amount'];
//                $updatePay['create_time'] = $orderInfo['create_time'];
//                $updatePay['pay_type'] = 2;
//                $updatePay['transaction_id'] = $returnData['trade_no'];
//                $updatePay['pay_time'] = time();
//				$resPay = $mPay->update($updatePay);
//                if($resPay === false){
//                    wLog('add pay error:'.M()->_sql(),'AlipayNotify');
//                    return false;
//                }
//                echo 'success';
//				try {
//					// 回调支付成功的方法
//					R($moduleInfo['notify_method'], array($orderInfo['order_id'], $accountId));
//				} catch (ThinkException $ex) {
//					wLog('error-msg:' . $ex->getMessage(), 'AlipayNotify');
//				}
			}
		}
	}

    public function test()
    {
        R('ModuleName/ActionName/functionName', array(12307));

//        $module = 'Restaurant/ZduRestaurant';
//        $action =  'notify';
//        $class  =  A($module,'');
//        var_dump($class);
    }
}